import axios, { type AxiosRequestConfig } from 'axios'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { useUserStore } from '@/stores/modules'
import router from '@/router'
const service = axios.create({
  baseURL: '/api',
  timeout: 5000,
})
// loading 次数
let loadingCount = 0

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()

    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    // 加入Loading
    showLoadingToast({
      message: '加载中...',
      //禁止背景点击
      forbidClick: true,
    })
    loadingCount++
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response) => {
    // 关闭loading
    loadingCount--
    if (loadingCount === 0) {
      closeToast()
    }

    if (
      response.config?.responseType === 'blob' &&
      (response.data.code ?? response.data instanceof Blob)
    ) {
      console.log(response.data.type,'type!!!')
      // 处理导出时后·端返回错误信息
      if (response.data.type.includes('application/json')) {
        new Blob([response.data]).text().then((text) => {
          const result = JSON.parse(text)
          showToast({ message: result.msg, position: 'top' })
        })
        return Promise.reject()
      }
      return response.data
    }
    if (response.data.code == 500) {
      showToast({ message: response.data.msg, position: 'top' })
    } else if (response.data.code == 401) {
      showToast({ message: '登录状态已过期!', position: 'top' })
      router.push('/login')
    }

    return response.data
  },
  (error) => {
    console.log(error, '报错了')

    closeToast()
    // 处理异常情况，根据项目实际情况处理或不处理
    if (error && error.response) {
      // 根据约定的响应码处理
      switch (error.response.status) {
        case 403:
          error.message = '拒绝访问'
          break
        case 502:
          error.message = '服务器端出错'
          break
        default:
          error.message = `连接错误${error.response.status}`
      }
    } else {
      // 超时处理
      error.message = '服务器响应超时，请刷新当前页'
    }
    showToast({ message: error.message, position: 'top' })
    return Promise.resolve(error.response)
  },
)

function request(config: AxiosRequestConfig) {
  return service(config)
}

export default request
